package com.itheima.reggie.common;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * springmvc 拦截器
 * 1.编写一个类,实现HandlerInterceptor
 * 2.配置拦截器,拦截路径/*
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断用户是否登录(看session中有没有employee),如果登录就放行
        Long employeeId =(Long) request.getSession().getAttribute("employee");
        Long userId =(Long) request.getSession().getAttribute("user");
        if (employeeId!=null){
            //员工登录成功的情况下,需要将员工id存入到本地线程中ThreadLocal
            BaseContext.setCurrentId(employeeId);
            return true;
        }
        if (userId!=null){
            //员工登录成功的情况下,需要将员工id存入到本地线程中ThreadLocal
            BaseContext.setCurrentId(userId);
            return true;
        }

        //表示用户没有登录,告诉前端,本次请求访问未登录,被拒接处理,响应code=0,msg=NOTLOGIN
            String json = JSON.toJSONString(R.error("NOTLOGIN"));
            response.getWriter().write(json);
            return false;
    }

    //controller方法执行完响应之后.最终结束后清理线程
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理本地线程中的数据
        BaseContext.removeCurrentId();
    }
}
